<template>
  <div :class="{'mobile-create': showMobilePage}" class="create-payBack-wrap">
    <div class="page-container">
      <Title title="基础信息" style="margin-bottom: 16px;" />
      <el-form
        ref="baseForm"
        :rules="rules"
        :model="paramsObj"
        :label-position="formAlign"
        class="lineHeight32"
        label-width="110px">
        <el-row class="response-el-row" type="flex">
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="发票类型" prop="invoiceType">
              <el-select v-model="paramsObj.invoiceType" filterable size="small" class="width240" popper-class="panel-auto-width" placeholder="请选择">
                <el-option
                  v-for="item in invoiceTypeOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="发票代码" prop="invoiceCode">
              <el-input v-model="paramsObj.invoiceCode" :maxlength="20" class="width240" placeholder="请输入发票代码" size="small" @input="numInputChange($event, 'invoiceCode')"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="发票号码" prop="invoiceNo">
              <div class="flex-center width240">
                <el-input v-model="paramsObj.invoiceNo" :maxlength="20" :disabled="!!id" placeholder="请输入发票号码" size="small" @input="numInputChange($event, 'invoiceNo')"/>
                <ImportButton
                  :import-api="'/admin/inputInvoice/ocr'"
                  :before-prop="true"
                  :before-prop-func="beforeUpload"
                  :hide-confirm="true"
                  :file-size="invoiceFileSize"
                  :is-disabled="uploadLoading"
                  is-diy
                  style="margin-left:8px;height:32px;margin-top:-2px;"
                  accept=".jpg,.jpeg,.png,.pdf,.bmp"
                  type="uploadFile"
                  @complateSetData="successUpload"
                  @onError="errorUpload">
                  <!-- <el-button :loading="uploadLoading" size="small" type="primary" class="ocr-btn">
                    <span class="flex-center">上传识别<tipIcon class="ml5" content="支持JPG/JPEG/PNG/PDF/BMP五种文件类型的发票识别"/></span>
                  </el-button> -->
                  <div class="flex-center">
                    <el-button :loading="uploadLoading" size="small" type="primary" class="ocr-btn">上传识别</el-button>
                    <tipIcon class="ml5" content="支持JPG/JPEG/PNG/PDF/BMP五种文件类型的发票识别"/>
                  </div>
                </ImportButton>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="开票日期" prop="invoiceDate">
              <el-date-picker
                v-model="paramsObj.invoiceDate"
                type="date"
                value-format="timestamp"
                size="small"
                class="width240"
                format="yyyy/MM/dd"
                placeholder="选择日期" />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="销方名称" prop="sellerName">
              <el-input v-model="paramsObj.sellerName" :maxlength="200" class="width240" placeholder="请输入销方名称" size="small" />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="销方税号">
              <el-input v-model="paramsObj.channelTaxId" :maxlength="100" class="width240" placeholder="请输入销方税号" size="small"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="地址">
              <el-input v-model="paramsObj.address" :maxlength="200" class="width240" placeholder="请输入地址" size="small" />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="电话">
              <el-input v-model="paramsObj.telephone" :maxlength="50" class="width240" placeholder="请输入电话" size="small" />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="开户行">
              <el-input v-model="paramsObj.bank" :maxlength="100" class="width240" placeholder="请输入开户行" size="small" />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="开户账号">
              <el-input v-model="paramsObj.bankAccount" :maxlength="100" class="width240" placeholder="请输入开户账号" size="small" />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="业务会计" prop="applicantId">
              <selectWithUserLoad
                ref="proposerRef"
                v-model="paramsObj.businessAccountingObj"
                :hide-select-list="paramsObj.businessAccountingId && paramsObj.businessAccounting?[{id: paramsObj.businessAccountingId, userName: paramsObj.businessAccounting}] : []"
                :multiple="false"
                :value-type="'object'"
                :show-check-user="true"
                key-name="id"
                class="width240"
                label-name="userName"
                filterable
                @change="proposerChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="跟进人" prop="applicantId">
              <selectWithUserLoad
                v-model="paramsObj.followUsers"
                :default-list="paramsObj.followUsers || []"
                :value-type="'object'"
                :extend-params="{ dimissionStatus: 1 }"
                key-name="id"
                style="width:240px;"
                label-name="userName"
                placeholder="请选择跟进人"
                multiple
                filterable
                collapse-tags
                clearable
                class="mb10"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <Title title="开票信息" style="margin-bottom: 16px;" />
      <el-form
        ref="invoiceForm"
        :rules="rules"
        :model="paramsObj"
        :label-position="formAlign"
        class="lineHeight32"
        label-width="110px">
        <el-row class="response-el-row" type="flex">
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="发票项目" prop="invoiceProject">
              <el-input v-model="paramsObj.invoiceProject" :maxlength="100" class="width240" placeholder="货物或应税劳务、服务名称" size="small" />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="单位">
              <el-input v-model="paramsObj.unit" :maxlength="50" class="width240" placeholder="请输入单位" size="small" />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="规格型号">
              <el-input v-model="paramsObj.specification" :maxlength="50" class="width240" placeholder="请输入规格型号" size="small" />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="数量">
              <el-input v-model="paramsObj.quantity" :maxlength="9" class="width240" placeholder="请输入数量" size="small" @input="numInputChange($event, 'quantity')"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="单价(元)">
              <el-input v-model="paramsObj.unitPrice" :maxlength="12" class="width240" placeholder="请输入单价" size="small" @input="numInputChange($event, 'unitPrice')"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="不含税金额(元)">
              <div class="sub-tip-box">
                <el-input v-model="paramsObj.money" :maxlength="12" class="width240" placeholder="请输入不含税金额" size="small" @input="handleAmount($event, 'money')"/>
                <div class="input-sub-tip">
                  <span>自动计算参考值：{{ money }}</span>
                  <el-tooltip :open-delay="800" placement="top" effect="dark">
                    <div slot="content" style="max-width: 210px">不含税金额=含税金额-税额</div>
                    <tipIcon is-diy style="position:relative;top:2px;"/>
                  </el-tooltip>
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="税率">
              <div class="sub-tip-box">
                <el-input v-model="paramsObj.taxRate" :maxlength="7" class="width240" placeholder="请输入税额" size="small" @input="handleAmount($event, 'taxRate')">
                  <i slot="suffix" style="color:#333">%</i>
                </el-input>
                <div class="input-sub-tip">
                  <span>自动计算参考值：{{ taxRate }}</span>
                  <el-tooltip :open-delay="800" placement="top" effect="dark">
                    <div slot="content" style="max-width: 210px">税率=税额/不含税金额</div>
                    <tipIcon is-diy style="position:relative;top:2px;"/>
                  </el-tooltip>
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="税额(元)" prop="taxAmount">
              <el-input v-model="paramsObj.taxAmount" :maxlength="12" class="width240" placeholder="请输入税额" size="small" @input="handleAmount($event, 'taxAmount')"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="含税金额(元)" prop="invoicePrice">
              <el-input v-model="paramsObj.invoicePrice" :maxlength="12" class="width240" placeholder="请输入含税金额" size="small" @input="handleAmount($event, 'invoicePrice')" @change="formatInvoicePrice"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8 indentation-form-item">
            <el-form-item label="实际销方名称" prop="realChannelName">
              <el-input v-model="paramsObj.realChannelName" :maxlength="200" class="width240" placeholder="请输入实际销方名称" size="small" />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="购方名称" prop="buyerName">
              <el-select
                v-model="paramsObj.buyerName"
                name="ourTitle"
                placeholder="购方名称"
                class="width240"
                size="small"
                popper-class="global-select-down panel-auto-width">
                <el-option
                  v-for="item in ourTitleList"
                  :key="item.id"
                  :label="item.label"
                  :value="item.label" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item :required="[2,3].includes(paramsObj.invoiceType)" label="票据附件">
              <upAttachment
                ref="uploadImg"
                :import-api="'/common/file/upload'"
                :hide-confirm="true"
                :is-disabled="false"
                :file-list="paramsObj.attachmentUrl"
                :limit="1"
                btn-text="上传附件"
                class="width240"
                @upProgress="upProgress"
                @complateSetData="complateSetData"
                @removeFileList="removeFileList"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <Title title="认证信息" style="margin-bottom: 16px;" />
      <el-form
        ref="certificateForm"
        :model="paramsObj"
        :label-position="formAlign"
        class="lineHeight32"
        label-width="110px">
        <el-row class="response-el-row" type="flex">
          <el-col :span="12" class="responsive-col-lg-8 indentation-form-item">
            <el-form-item label="进项认证抵扣期">
              <el-date-picker
                v-model="paramsObj.certifyDeductPeriod"
                type="date"
                value-format="timestamp"
                size="small"
                class="width240"
                format="yyyy/MM/dd"
                placeholder="选择日期" />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item :class="{ 'flex-item': showMobilePage }" label="抵扣税额(元)">
              <el-input v-model="paramsObj.deductTaxAmount" disabled class="width240" placeholder="=税额-进项税额转出" size="small" />
              <el-tooltip :open-delay="800" placement="top" effect="dark">
                <div slot="content" style="max-width: 210px">抵扣税额=税额-进项税额转出</div>
                <tipIcon is-diy style="position:relative;top:2px;"/>
              </el-tooltip>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="文建抵扣期">
              <el-date-picker
                v-model="paramsObj.culturalConstructDeductPeriod"
                type="date"
                value-format="timestamp"
                size="small"
                class="width240"
                format="yyyy/MM/dd"
                placeholder="选择日期" />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8 indentation-form-item">
            <el-form-item :class="{ 'flex-item': showMobilePage }" label="文建抵扣金额(元)">
              <el-input v-model="paramsObj.deductAmount" disabled class="width240" placeholder="=含税金额-不可抵文建金额" size="small" />
              <el-tooltip :open-delay="800" placement="top" effect="dark">
                <div slot="content" style="max-width: 210px">文建抵扣金额=含税金额-不可抵文建金额</div>
                <tipIcon is-diy style="position:relative;top:2px;"/>
              </el-tooltip>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8 indentation-form-item">
            <el-form-item label="不可抵文建金额(元)">
              <el-input v-model="paramsObj.nonCulturalConstructAmount" :maxlength="12" class="width240" placeholder="请输入不可抵文建金额" size="small" @input="handleDeductionAmount($event, 'nonCulturalConstructAmount')"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8 indentation-form-item">
            <el-form-item label="进项税额转出(元)">
              <el-input v-model="paramsObj.taxTransferOut" :maxlength="12" class="width240" placeholder="<=税额" size="small" @input="handleInputTaxOut($event, 'taxTransferOut')"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8 indentation-form-item">
            <el-form-item label="进项税额转出原因">
              <el-input v-model="paramsObj.taxTransferOutReason" :maxlength="500" class="width240" placeholder="请输入进项税额转出原因" size="small" />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8 indentation-form-item">
            <el-form-item label="进项税额转出期">
              <el-date-picker
                v-model="paramsObj.taxTransferOutDate"
                type="date"
                value-format="timestamp"
                size="small"
                class="width240"
                format="yyyy/MM/dd"
                placeholder="选择日期" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <fixed-pagination class="mobile-input-fix">
      <el-alert
        v-if="id"
        title="小提示：保存将同步至付款申请"
        type="warning"
        class="tip"
        show-icon/>
      <div class="center">
        <el-button :loading="saveLoading" type="primary" size="small" plain class="empty-btn-style" @click="handleSave">保存</el-button>
        <el-button type="info" size="small" class="back-btn cancel-btn-style" @click="handleBack">返回</el-button>
      </div>
    </fixed-pagination>
  </div>
</template>

<script>
import { invoiceTypeOption } from './options';
import Title from '@/components/Title';
import upAttachment from '@/components/Common/upAttachment/index';
import { getInputInvoiceDetail, editInputInvoice, addInputInvoice } from '@/api/inputInvoice';
import ElMessage from '@/utils/message';
import { getIssueOurTitleList } from '@/api/issueInvoice';
import selectWithUserLoad from '@/components/Common/selectWithUserLoad';
import mobileCreate from '@/mixins/mobileCreate';
import ImportButton from '@/components/ImportButton';

export default {
  components: { Title, upAttachment, selectWithUserLoad, ImportButton },
  mixins: [mobileCreate],
  data() {
    return {
      invoiceTypeOption,
      rules: {
        'invoiceType': [{ required: true, message: '请选择发票类型', trigger: 'change' }],
        'invoiceCode': [{ required: true, message: '请输入发票代码', trigger: 'blur' }],
        'invoiceNo': [{ required: true, message: '请输入发票号码', trigger: 'blur' }],
        'invoiceDate': [{ required: true, message: '请选择开票日期', trigger: 'change' }],
        'sellerName': [{ required: true, message: '请输入销方名称', trigger: 'blur' }],
        'invoiceProject': [{ required: true, message: '请输入货物或应税劳务、服务名称', trigger: 'blur' }],
        'taxAmount': [{ required: true, message: '请输入税额', trigger: 'blur' }],
        'invoicePrice': [{ required: true, message: '请输入含税金额', trigger: 'blur' }],
        'realChannelName': [{ required: true, message: '请输入实际销方名称', trigger: 'blur' }],
        'buyerName': [{ required: true, message: '请输入购方名称', trigger: 'change' }]
      },
      paramsObj: {
        attachmentUrl: [],
        quantity: 1,
        taxAmount: null,
        followUsers: []
      },
      ourTitleList: [],
      id: '',
      money: 0,
      taxRate: '--',
      saveLoading: false,
      uploadLoading: false,
      fieldsMap: {
        invoice_code: { key: 'invoiceCode', type: 'string' },
        invoice_no: { key: 'invoiceNo', type: 'string' },
        total_price: { key: 'money', type: 'money' },
        total_tax: { key: 'taxAmount', type: 'money' },
        total_price_and_tax: { key: 'invoicePrice', type: 'money' },
        buyer_name: { key: 'buyerName', type: 'select' },
        seller_taxpayer_no: { key: 'channelTaxId', type: 'string' },
        seller_address_phone: { key: 'address', keyName: '地址', subKey: 'telephone', subName: '电话', type: 'doubleFields' },
        seller_account: { key: 'bank', keyName: '开户行', subKey: 'bankAccount', subName: '开户账号', type: 'doubleFields' },
        seller_name: { key: 'sellerName', type: 'string' },
        invoice_date: { key: 'invoiceDate', type: 'date' }
      },
      invoiceFileSize: 0,
      ocrMsg: ''
    };
  },
  created() {
    if (this.$route.query.id) {
      this.id = this.$route.query.id;
      this.getDetailData();
    }
    this.queryOurTitleList();
  },
  methods: {
    queryOurTitleList() {
      getIssueOurTitleList().then(res => {
        if (res.code === 200) {
          const result = res.data || [];
          result.forEach(item => {
            item.value = item.id;
            item.label = item.name;
            item.isStringVal = true;
            item.name = '我方抬头';
          });
          this.ourTitleList = result;
        }
      });
    },
    formatDisabledData() {
      const taxAmount = Number((this.paramsObj.taxAmount === '-' ? 0 : this.paramsObj.taxAmount) || 0);
      const invoicePrice = Number((this.paramsObj.invoicePrice === '-' ? 0 : this.paramsObj.invoicePrice) || 0);
      this.money = (invoicePrice - taxAmount).toFixed(2);
      this.taxRate = this.paramsObj.money ? ((taxAmount / this.paramsObj.money) * 100).toFixed(2) + '%' : '--';
      if (this.paramsObj.taxTransferOut && Number(this.paramsObj.taxTransferOut) > taxAmount) {
        this.paramsObj.taxTransferOut = taxAmount;
        ElMessage.warning('进项税额转出<=税额！');
      }
      this.paramsObj.deductTaxAmount = (taxAmount - Number(this.paramsObj.taxTransferOut || 0)).toFixed(2);
      this.paramsObj.deductAmount = (invoicePrice - Number(this.paramsObj.nonCulturalConstructAmount || 0)).toFixed(2);
    },
    async getDetailData() {
      try {
        const { data } = await getInputInvoiceDetail(this.id);
        data.quantity = data.quantity || 1;
        data.invoiceDate = data.invoiceDate ? data.invoiceDate * 1000 : null;
        data.certifyDeductPeriod = data.certifyDeductPeriod ? data.certifyDeductPeriod * 1000 : null;
        data.taxTransferOutDate = data.taxTransferOutDate ? data.taxTransferOutDate * 1000 : null;
        data.culturalConstructDeductPeriod = data.culturalConstructDeductPeriod ? data.culturalConstructDeductPeriod * 1000 : null;
        this.paramsObj = data;
        this.paramsObj.businessAccountingObj = {
          id: data.businessAccountingId,
          userName: data.businessAccounting
        };
        this.formatDisabledData();
      } catch (err) {
        console.log(err);
      }
    },
    handleAmount(text, prop) {
      this.numInputChange(text, prop);
      this.formatDisabledData();
    },
    handleInputTaxOut(text, prop) {
      this.numInputChange(text, prop);
      const taxAmount = Number((this.paramsObj.taxAmount === '-' ? 0 : this.paramsObj.taxAmount) || 0);
      if (Number(this.paramsObj.taxTransferOut) > taxAmount) {
        this.paramsObj.taxTransferOut = taxAmount;
        ElMessage.warning('进项税额转出<=税额！');
      }
      this.paramsObj.deductTaxAmount = (taxAmount - Number(this.paramsObj.taxTransferOut)).toFixed(2);
    },
    handleDeductionAmount(text, prop) {
      this.numInputChange(text, prop);
      this.paramsObj.deductAmount = (Number((this.paramsObj.invoicePrice === '-' ? 0 : this.paramsObj.invoicePrice) || 0) - Number(this.paramsObj.nonCulturalConstructAmount || 0)).toFixed(2);
    },
    numInputChange(text, prop) {
      let str;
      if (['invoicePrice', 'taxAmount', 'taxTransferOut'].includes(prop)) {
        str = text.replace(/[^\-?\d.]/g, ''); // 含税金额，税额，进项税额转出允许正负数字
      } else {
        str = text.replace(/[^\d.]/g, ''); // 只允许数字
      }
      if (prop === 'quantity') {
        str = str.replace(/\.|^0/g, ''); // 数量只允许输入正整数
      } else if (['invoiceCode', 'invoiceNo'].includes(prop)) {
        str = str.replace(/[^\d]/g, ''); // 发票代码,发票号码只允许输入数字
      } else {
        str = str.replace(/\.{2,}/g, '.'); // 连续两个小数点 replace为.
        str = str.replace(/^\./g, '0.'); // 已点为开头 replace为 0.
        str = str.replace(/^(\d*)\.(\d*)\./g, '$1.$2');// 不连续点点 删掉
        str = str.replace(/^0[^\.]+/g, '0'); // 连续多个0 replace为1个0
        str = str.replace(/^(\-?\d+)\.(\d\d).*$/, '$1.$2'); // 只允许保留小数点后2位
        if (prop === 'taxRate') {
          str = Number(str) > 9999.99 ? 9999.99 : str;
        }
      }
      str = str === '' ? null : str;
      this.paramsObj[prop] = str;
    },
    formatInvoicePrice(val) {
      if (Number(val) === 0) {
        ElMessage.warning('含税金额不能输入为0');
        this.paramsObj.invoicePrice = '';
      }
    },
    upProgress() {
      this.createLoading = true;
    },
    complateSetData({ data, fileName }) {
      this.createLoading = false;
      const fileList = {
        name: fileName,
        url: data.url,
        time: new Date().getTime()
      };
      if (typeof data === 'string') {
        fileList.url = data;
      } else {
        fileList.url = data.url;
      }
      !this.paramsObj.attachmentUrl && (this.paramsObj.attachmentUrl = []);
      this.paramsObj.attachmentUrl.push(fileList);
    },
    removeFileList({ file, index }) {
      this.paramsObj.attachmentUrl.splice(index, 1);
    },
    handleSave() {
      try {
        const params = [];
        params.push(this.$refs.baseForm.validate());
        params.push(this.$refs.invoiceForm.validate());
        Promise.all(params).then(res => {
          const validateResult = res.every(item => !!item);
          if (validateResult) {
            if ([2, 3].includes(this.paramsObj.invoiceType) && (!this.paramsObj.attachmentUrl || this.paramsObj.attachmentUrl.length === 0)) {
              ElMessage.error('请上传票据附件！');
              return;
            }
            // 含税金额和税额同正同负校验
            if (this.paramsObj.invoicePrice * this.paramsObj.taxAmount < 0) {
              ElMessage.warning('含税金额与税额存在错误，应同正同负！');
              return;
            }
            const params = JSON.parse(JSON.stringify(this.paramsObj));
            if (params.followUsers) {
              params.followUsers = params.followUsers.map(item => item.id);
            }
            this.id ? this.edit(params) : this.add(params);
          } else {
            return false;
          }
        }).catch((error) => {
          ElMessage.warning('请检查信息是否填写完整');
          console.log('error', error);
        });
      } catch (error) {
        console.log(error);
      }
    },
    add(params) {
      this.saveLoading = true;
      addInputInvoice(params).then(res => {
        this.saveLoading = false;
        if (res.code === 200) {
          this.$router.push({ name: 'inputInvoiceDetail', query: { id: res.data }});
          ElMessage.success('新建成功');
        }
      }).catch(err => {
        this.saveLoading = false;
        console.log(err);
      });
    },
    edit(params) {
      this.saveLoading = true;
      editInputInvoice(params).then(res => {
        this.saveLoading = false;
        if (res.code === 200) {
          this.$router.push({ name: 'inputInvoiceDetail', query: { id: this.id }});
          ElMessage.success('修改成功');
        }
      }).catch(err => {
        this.saveLoading = false;
        console.log(err);
      });
    },
    handleBack() {
      this.$router.go(-1);
    },
    proposerChange(data) {
      this.paramsObj.businessAccountingId = data.id;
      this.paramsObj.businessAccounting = data.userName;
      // this.paramsObj.avatar = data.avatar;
    },
    beforeUpload(file) {
      if (this.uploadLoading) {
        return Promise.reject();
      }
      this.ocrMsg = '';
      if (file) {
        this.uploadLoading = true;
        this.invoiceFileSize = file.size;
        const res = /\.jpe?g$|\.png$|\.pdf$|\.bmp$/i.test(file.name);
        if (!res) {
          this.uploadLoading = false;
          ElMessage.warning('请注意只能上传【jpg/jpeg/png/pdf/bmp】类型文件！');
          return Promise.reject();
        }
      }
    },
    successUpload(val) {
      // 填充返回字段
      this.uploadLoading = false;
      if (val.data && val.data.vat_invoices && val.data.vat_invoices.length && val.data.vat_invoices[0] && val.data.vat_invoices[0].entities) {
        const invoiceData = val.data.vat_invoices[0].entities;
        for (let i = 0; i < invoiceData.length; i++) {
          const typeData = this.fieldsMap[invoiceData[i].type];
          if (typeData && invoiceData[i].value) {
            this.typeFillIn(typeData, invoiceData[i]);
          }
        }
        this.$refs.baseForm.clearValidate();
        this.$refs.invoiceForm.clearValidate();
        this.formatDisabledData();
        if (this.ocrMsg) {
          ElMessage.warning({ dangerouslyUseHTMLString: true, message: this.ocrMsg });
        }
      }
      if (val.data && val.data.attachment) {
        this.$set(this.paramsObj, 'attachmentUrl', [val.data.attachment]);
      }
    },
    typeFillIn(typeData = {}, data = {}) {
      if (typeData.type === 'string') {
        this.$set(this.paramsObj, typeData.key, data.value);
      } else if (typeData.type === 'money') {
        // 不能截取第一个字符,因为飞书ocr识别有些会返回¥,有些不会返回
        // const temp = data.value.slice(1);
        // 不用替换第一个字符,因为飞书识别返回的金额符号不是标准的
        // const temp = data.value.replace(/^¥|^Ұ|^￥/, '');
        const temp = data.value.match(/\d+\.?\d+/);
        if (temp) {
          this.$set(this.paramsObj, typeData.key, Number(temp[0]));
        }
      } else if (typeData.type === 'date') {
        // 提取年、月、日
        const match = data.value.match(/(\d{4})年(\d{2})月(\d{2})日/);
        const date = new Date(parseInt(match[1]), parseInt(match[2]) - 1, parseInt(match[3]));
        this.$set(this.paramsObj, typeData.key, date.getTime());
      } else if (typeData.type === 'doubleFields') {
        const arr = data.value.split(' ');
        if (arr[0]) {
          this.$set(this.paramsObj, typeData.key, arr[0]);
        } else {
          this.ocrMsg += `<p style="margin-bottom:8px;">${typeData.keyName}未识别成功，请手动输入</p>`;
        }
        if (arr[1]) {
          this.$set(this.paramsObj, typeData.subKey, arr[1]);
        } else {
          this.ocrMsg += `<p style="margin-bottom:8px;">${typeData.subName}未识别成功，请手动输入</p>`;
        }
      } else if (typeData.type === 'select') {
        const temp = this.ourTitleList.findIndex(item => item.label === data.value);
        if (temp !== -1) {
          this.$set(this.paramsObj, typeData.key, data.value);
        } else {
          this.ocrMsg += '<p style="margin-bottom:8px;">不存在该供应商，请先添加供应商后再进行识别</p>';
        }
      }
    },
    errorUpload(val) {
      this.uploadLoading = false;
      ElMessage.error(val);
    }
  }
};
</script>

<style lang="scss" scoped>
.create-payBack-wrap{
  margin: 16px;
	background: #FFFFFF;
	min-height: calc(100vh - 56px);
  padding-bottom: 56px;
  .empty-btn-style {
    border-color: #406EFF;
    background: #fff;
    color: #406EFF;
    width: 80px;
    padding: 7px 0;
    text-align: center;
  }
  .width240 {
    width: 240px;
  }
  .page-container{
    padding: 20px 24px 24px;
    &::v-deep {
      .el-form-item .el-form-item__label {
        color: #666;
      }
      .el-form-item .el-form-item__content {
        color: #333;
      }
    }
    .sub-tip-box {
      width: 240px;
      position: relative;
      .input-sub-tip {
        font-size: 12px;
        color: #999;
        position: absolute;
        top: 26px;
        right: 0;
      }
    }
  }
  &.mobile-create {
    .sub-tip-box {
      width: auto;
    }
    .mobile-input-fix {
      overflow: unset !important;
      .center {
        ::v-deep .el-button {
          flex: 1;
        }
      }
    }
    .flex-item {
      &::v-deep {
        .el-form-item__content {
          display: flex;
          .el-tooltip {
            top: 10px !important;
            margin-left: 5px;
          }
        }
      }
    }
  }
  .tip {
    position: absolute;
    bottom: 56px;
    right: calc(50% + 52px);
    transform: translateX(50%);
    width: 220px;
    padding: 5px 8px;
    background: #FFF8EA;
    ::v-deep {
      .el-alert__content {
        padding: 0 8px 0 4px;
      }
      .el-alert__title {
        font-size: 10px;
        color: #333333;
        font-weight: 400;
      }
      .el-alert__closebtn {
        top: 10px;
        right: 8px;
      }
    }
  }
}
::v-deep .indentation-form-item {
  .el-form-item {
    label {
      line-height: 1.2 !important;
    }
  }
}
.ocr-btn {
  padding: 7px;
}
</style>
